<?php
namespace app\controllers;

use app\models\OrderModel;
use yii;

class PaymentController extends ApiBaseController
{
    /**
     *创建paypal支付链接
     *
     */
    public function actionPaypalLink()
    {
        $orderNum = yii::$app->request->post('order_num', '');
        if (!$orderNum) {
            return false;
        }
        $model = new OrderModel();
        $order = $model->one(['order_num' => $orderNum]);
        if (!$order) {
            return json_encode(['code' => 0, 'msg' => '订单不存在']);
        }
        if ($order['have_pay'] == 2 || $order['have_pay'] == 3) {
            return json_encode(['code' => 0, 'msg' => '订单已经支付或被取消']);
        }
        $clientId   = PAYPAL_CLIENT_ID;
        $secret     = PAYPAL_SECRET;
        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                $clientId, // ClientID
                $secret // ClientSecret
            )

        );
        $config = [
            'log.LogEnabled' => true,
            'log.FileName'   => 'PayPal.log',
            'log.LogLevel'   => 'DEBUG',
            'mode'           => 'live',
            'cache.enabled'  => true,
        ];
        $apiContext->setConfig($config);
        $orderItem = \json_decode($order['items'], true);
        $itemArr   = [];
        foreach ($orderItem as $v) {
            $item = new \PayPal\Api\Item();
            $item->setName($v['item'])
                ->setCurrency('USD')
                ->setQuantity($v['num'])
                ->setPrice($v['price']);
            array_push($itemArr, $item);
        }

        $itemList = new \PayPal\Api\ItemList();
        $itemList->setItems($itemArr);

        $payer = new \PayPal\Api\Payer();
        $payer->setPaymentMethod('paypal');

        $amount = new \PayPal\Api\Amount();
        $amount->setCurrency('USD');
        $amount->setTotal($order['total_money']);

        $transaction = new \PayPal\Api\Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription($order['remark'])
            ->setInvoiceNumber($order['order_num'])
            ->setNotifyUrl(PAYPAL_NOTIFY_URL);

        $redirectUrls = new \PayPal\Api\RedirectUrls();
        $redirectUrls->setReturnUrl(PAYPAL_RETURN_URL)
            ->setCancelUrl("https://example.com/your_cancel_url.html");

        $payment = new \PayPal\Api\Payment();
        $payment->setIntent('sale')
            ->setPayer($payer)
            ->setTransactions(array($transaction))
            ->setRedirectUrls($redirectUrls);

        try {
            $payment->create($apiContext);

            $url = $payment->getApprovalLink();
            return json_encode(['code' => 1, 'msg' => 'success', 'url' => $url]);
        } catch (\PayPal\Exception\PayPalConnectionException $ex) {
            // This will print the detailed information on the exception.
            //REALLY HELPFUL FOR DEBUGGING
            return new \Exception($ex->getMessage());
        }
    }
}
